<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Greetings</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<body>
<p th:text="'Hello, ' + ${title}"></p><br/>
<p>【操作】：
<!--<div style="border: 1px saddlebrown solid;width: 150px;"><a onclick="openSocket()">开启socket</a></div>-->
<button onclick="readMsg()" style="margin-top: 30px;">接收服务端主动推送的消息</button>
</body>

<script>
    let lockReconnect = false;  //避免ws重复连接
    let ws = null;          // 判断当前浏览器是否支持WebSocket
    let wsUrl = "ws://localhost:8080/socket";
    createWebSocket(wsUrl);   //连接ws
    let socket;

    function createWebSocket(url) {
        try {
            if ('WebSocket' in window) {
                ws = new WebSocket(url);
            }
            initEventHandle();
        } catch (e) {
            reconnect(url);
            console.log(e);
        }
    }

    function initEventHandle() {
        ws.onclose = function () {
            reconnect(wsUrl);
            console.log("llws连接关闭!" + new Date().toLocaleString());
        };
        ws.onerror = function () {
            reconnect(wsUrl);
            console.log("llws连接错误!");
        };
        ws.onopen = function () {
            heartCheck.reset().start();      //心跳检测重置
            console.log("llws连接成功!" + new Date().toLocaleString());
        };
        ws.onmessage = function (event) {    //如果获取到消息，心跳检测重置
            heartCheck.reset().start();      //拿到任何消息都说明当前连接是正常的
            console.log("llws收到消息啦:" + event.data);
            if (event.data !== 'pong') {
                let data = JSON.parse(event.data);
            }
        };
    }

    function reconnect(url) {
        if (lockReconnect) return;
        lockReconnect = true;
        setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
            createWebSocket(url);
            lockReconnect = false;
        }, 2000);
    }

    //心跳检测
    let heartCheck = {
        timeout: 1000,        //1分钟发一次心跳
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () {
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
        },
        start: function () {
            let self = this;
            this.timeoutObj = setTimeout(function () {
                //这里发送一个心跳，后端收到后，返回一个心跳消息，
                //onmessage拿到返回的心跳就说明连接正常
                ws.send("ping");
                console.log("ping!")
                self.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置，说明后端主动断开了
                    ws.close();     //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                }, self.timeout)
            }, this.timeout)
        }
    }

    function openSocket() {
        if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
            //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
            //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
            var socketUrl = "ws://localhost:8080/socket";
            //socketUrl=socketUrl.replace("https","ws");
            if (socket != null) {
                socket.close();
                socket = null;
            }
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function () {
                console.log("websocket已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            socket.onmessage = function (msg) {
                console.log(msg.data);
                //发现消息进入    开始处理前端触发逻辑
            };
            //关闭事件
            socket.onclose = function () {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function () {
                console.log("websocket发生了错误");
            }
        }
    }

    function readMsg() {
        // alert("think");
        $.ajax({
            url: "/send",
            type: "GET",
            dataType: "json",
            success: function (data) {
                console.log(data);
            }
        })
    }

    // function sendMessage() {
    //     if(typeof(WebSocket) == "undefined") {
    //         console.log("您的浏览器不支持WebSocket");
    //     }else {
    //         console.log("您的浏览器支持WebSocket");
    //         console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
    //         socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
    //     }
    // }
</script>
</html>